#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <time.h>

void *handle(void *fd) {

		int client_sockfd;
		char char_recv[30];
		client_sockfd = *((int*)fd);
		int ret = recv(client_sockfd, char_recv, 30, 0);
		time_t t;
		time(&t);		


		if(ret > 0){

		char_recv[ret] = '\0';
		printf("%s %s\n",ctime(&t),char_recv);
		}else{						
		printf("%s\n",ctime(&t));
		}


//printf("%s",ctime(&t));
		close(client_sockfd);

}

int main() {

		pthread_t child;
		char revData[30];
		int s_fd,c_fd;
		struct sockaddr_in s_add,c_add;

		s_fd = socket(AF_INET, SOCK_STREAM, 0);
		if(-1 == s_fd) {

				printf("socket fail\n");
				return -1;
		}

		bzero(&s_add, sizeof(struct sockaddr_in));
		s_add.sin_family = AF_INET;
		s_add.sin_addr.s_addr = htonl(INADDR_ANY);
		s_add.sin_port = htons(1234);

		if(-1 == bind(s_fd, (struct sockaddr *)(&s_add),sizeof(struct sockaddr))){

						printf("bind fail\n");
						return -1;
						}

						if(-1 == listen(s_fd, 5)){
								printf("listen fail");
								return -1;
								}
						printf("接受客户端中...\n");
						while(1) {

						int sin_size = sizeof(struct sockaddr_in);
						c_fd = accept(s_fd, (struct sockaddr *)(&c_add),&sin_size);
						if(-1 == c_fd) {

						printf("accept fail");
						return -1;
						}else {
						if(pthread_create(&child, NULL, handle, &c_fd) != 0) {
							printf("create thread fail\n");
							break;
						}

						}


						}


		close(s_fd);
		return 0;
}
